<template>
    <el-row id="cpts-collect-datas">
      <el-row v-if="!isViewShow" class="permission">
        没有权限!
      </el-row>
      <el-card v-else class="box-card">
      <div slot="header" class="clearfix">
        <span>采集数据管理</span>
        <el-button :disabled="!isViewEdit" style="float: right; padding: 6px 6px;margin-right: 10px" type="primary" @click="handleAdd">添加<i class="el-icon-plus el-icon--right"></i></el-button>
      </div>

      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%;"
        max-height="644">
        <el-table-column
          prop="nodeName"
          label="节点名称">
        </el-table-column>
        <el-table-column
          sortable
          :formatter="statusFormatter"
          prop="isCumulative"
          label="是否累计">
        </el-table-column>
        <el-table-column
          :formatter="isTableItemFormatter"
          sortable
          prop="isReportShow"
          label="是否统计表子项">
        </el-table-column>
        <el-table-column
          prop="description"
          label="备注">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间">
        </el-table-column>
        <el-table-column
          prop="createName"
          label="创建人">
        </el-table-column>
        <el-table-column label="操作"  align="center"  fixed="right"  width="180px">
          <template slot-scope="scope">
            <el-button :disabled="!isViewEdit"
                       type="mini"
                       size="text"
                       @click="handleInfo(scope.$index, scope.row)">详情</el-button>
           <!-- <el-button :disabled="!isViewEdit"
              size="mini"
              type="text"
              @click="handleHistory(scope.$index, scope.row)">历史</el-button>-->
            <el-button :disabled="!isViewEdit"
              size="mini"
              type="text"
              @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>

      </el-table>

      <!--分页-->
      <div style="text-align: center;margin-top: 10px;">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="paginationCount"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="onPageChange">
        </el-pagination>
      </div>
      </el-card>

      <!--添加弹窗-->
      <el-dialog :visible.sync="addDialogShow">
        <el-row slot="title">
          <span style="font-size: 18px">新增</span>
          <el-button @click="handleAddSubmit('ruleFormAdd')" style="margin-left: 1240px; padding: 6px 10px" type="primary"  :loading="false">提交</el-button>
        </el-row>
        <el-row>
          <el-collapse v-model="activeName" accordion>
            <el-collapse-item title="基础数据" name="1">
              <el-form  label-width="100px" >
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="节点名称">
                      <el-input v-model="addForm.nodeName" ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否累计">
                      <el-select v-model="addForm.isCumulative" placeholder="请选择">
                        <el-option
                          v-for="item in accumulativeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                   <el-col :span="8">
                     <el-form-item label="备注">
                       <el-input v-model="addForm.description" ></el-input>
                     </el-form-item>
                   </el-col>
                </el-row>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="是否报表展示">
                      <el-select @change="onIsReportSelect" v-model="addForm.isReportShow" placeholder="请选择">
                        <el-option
                          v-for="item in addTableOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" v-if="isChooseReport">
                    <el-form-item label="报表类型">
                      <el-select @change="onReportTypeChange" multiple collapse-tags v-model="addForm.customType" placeholder="请选择">
                        <el-option
                          v-for="item in addTableTypeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="单位">
                      <el-input v-model="addForm.unit"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-collapse-item>
            <el-collapse-item title="配置变量关系" name="2">
              <el-form  label-width="80px">
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="参数名">
                      <el-input v-model="itemAddForm.paramsName"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="变量绑定">
                      <el-select @change="onSelectChange" v-model="itemAddForm.attributeInfoId" placeholder="请选择" >
                        <el-option
                          v-for="item in tagBindOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-button style="padding: 12px 12px" type="primary" @click="addSettingItem">添加</el-button>
                  </el-col>
                </el-row><hr>

                <el-table
                  :data="addForm.collectedParameterConfigurationEntities"
                  stripe
                  max-height="310"
                  style="width: 100%">
                  <el-table-column
                    prop="parameter"
                    label="参数名">
                  </el-table-column>
                  <el-table-column
                    prop="tagName"
                    label="变量">
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="danger"
                        @click="handleItemDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table><hr style="margin-top: 20px;margin-bottom: 20px">

                <el-row>
                  <el-col :span="8">
                    <el-form-item label="计算关系" >
                      <el-input v-model="addForm.parameterCalculateRelationship" :rows="4" type="textarea" ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

              </el-form>
            </el-collapse-item>
          </el-collapse>
        </el-row>
      </el-dialog>

      <!--历史弹窗-->
     <!-- <el-dialog :visible.sync="historyDialogShow">
        <el-row slot="title">
          <span style="font-size: 18px">历史数据</span>
        </el-row>

        <el-row>
          <el-date-picker
            :type="pickerType"
            :value-format="histotyDateFormat"
            @change="onPickerChange"
            v-model="histotyDate"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-row>

        <el-row>
          <BaseEchartsComponent ref="cptsCdsLineChart" :id="'cpts-cds-chart'" :data="lineChartsOptions" />
        </el-row>

      </el-dialog>-->
    </el-row>


</template>


<script>
  import BaseEchartsComponent from "../BaseEcharts/index";
  import myEchartsOptions from '../../chart-options/echartsOptions'
  import {DateTime} from '../../utils/dateTime'
    export default {
        name: "collectDatas",
      components: {BaseEchartsComponent},
      data(){
          return {
            /*权限*/
            isViewShow: false,
            isViewEdit: false,
            fileName: '',
            /*分页*/
            paginationCount: 0,
            currentPage:1,
            pageSize:11,
            /*列表数据*/
            tableData: [{name: 1}],
            itemTableData: [{name: 1}],
            /*时间控件*/
            pickerType:'date',
            histotyDate: new Date(),
            histotyDateFormat: 'yyyy-MM-dd',
            /*面板激活*/
            activeName:['1'],
            /*弹窗*/
            addDialogShow:false,
            historyDialogShow: false,
            /*折线图*/
            lineChartsOptions: this.validateGlobal.cloneObject(myEchartsOptions.lineChartsOption),
            /*是否累计*/
            accumulative: '',
            accumulativeOptions:[{value: 0,label: '增量'},{value: 1,label: '累计'}],
            addTableValue: '',
            addTableOptions:[{value: 1,label: '是'},{value: 0,label: '否'}],
            addTableTypeOptions:[{value: '2',label: '日'},{value: '3',label: '月'},{value: '4',label: '年'},{value: '5',label: '供水时间段'}],
            tagBindOptions:[],
            /*条件筛选*/
            isReportShow:'',
            isCumulative: '',
            nodeName: '',
            /*添加表单*/
            addForm:{
              id: "",
              nodeName: "",
              tagCalculateRelationship: "",
              isReportShow: 0,
              isCumulative: 1,
              type: "2",
              customType: [],
              sn: "",
              description: "",
              unit: "",
              parameterCalculateRelationship: "",
              collectedParameterConfigurationEntities: []
            },
            /*子项添加表单*/
            itemAddForm:{
              attributeInfoId: '',
              paramsName: '',
              tagName: ''
            },
            /*tagList采集基础数据缓存*/
            tagList: [],
            /*是否显示报表类型*/
            isChooseReport: false
          }
      },
      mounted(){
        let _that = this
        let obj = this.validateGlobal.getPermission(6)
        this.isViewShow = obj.isViewShow
        this.isViewEdit = obj.isViewEdit

        this.lineChartsOptions.xAxis[0].data = []
        this.lineChartsOptions.series[0].data = []
        this.lineChartsOptions.xAxis[0].axisLine.lineStyle.color = '#000'
        this.lineChartsOptions.yAxis[0].axisLine.lineStyle.color = '#000'
        this.lineChartsOptions.grid.left = 80
        this.askLists()
        this.askTagList()
      },
      methods:{
        onReportTypeChange: function(value){
          if (value) {
            let multStr = ''
            for(let i = 0;i< value.length;++i){
              if (value.length === 1){
                multStr += value[i]
              }else{
                if (i == value.length-1){
                  multStr += value[i]
                }else{
                  multStr += (value[i]+ ",")
                }
              }
            }
            this.addForm.type = multStr
          }else{
            this.addForm.type = ''
          }
          this.$set(this.addForm,this.addForm.customType,this.$event)
        },
        onIsReportSelect: function(value){
          if (value == 1) {
            this.isChooseReport = true
          }else{
            this.isChooseReport = false
          }
        },
        statusFormatter: function(row, column){
          if (row.isCumulative === 0){
            return "增量"
          }else{
            return "累计"
          }
        },
        isTableItemFormatter: function(row, column){
          if (row.isReportShow === 0){
            return "否"
          }else{
            return "是"
          }
        },
        resetAddForm: function(){
          this.addForm = {
            id: "",
            nodeName: "",
            tagCalculateRelationship: "",
            isReportShow: 0,
            isCumulative: 1,
            type: "",
            customType: [],
            sn: "",
            description: "",
            unit: "",
            parameterCalculateRelationship: "",
            collectedParameterConfigurationEntities: []
          }
        },
        onSelectChange: function(value){
          let _that = this
          for(let i = 0;i< _that.tagList.length;++i){
            if (_that.tagList[i].id == value) {
              _that.itemAddForm.tagName = _that.tagList[i].tagName
            }
          }
        },
        handleAdd(){                          // 新增
          if (!this.addDialogShow) {
            this.addDialogShow = true
          }
          this.resetAddForm()
        },
        handleAddSubmit: function(formName){
          if (!this.addForm.nodeName){
            this.$message("请输入节点名称")
            return
          }
          if (!this.addForm.unit){
            this.$message("请输入节点单位")
            return
          }
          if (!this.addForm.collectedParameterConfigurationEntities){
            this.$message("请绑定变量")
            return
          }
          if (!this.addForm.parameterCalculateRelationship){
            this.$message("请输入变量关系")
            return
          }
          this.addTagNode()
        },
        handleInfo: function(index,row){      // 详情
          if (!this.addDialogShow) {
            this.addDialogShow = true
          }
          // this.addForm = row
          this.askInfo(row.id)
        },
        handleHistory: function(index,row){   // 历史
          if (!this.historyDialogShow) {
            this.historyDialogShow = true
          }
        },
        handleDelete: function(index,row){    // 删除
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let url = _that.ports.collectManage.collectData.delete
          let askData = {
            userId: userId,
            id: row.id
          }
          this.http.get(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.$message('删除成功!');
              _that.askLists()
            }else{
              _that.$message('删除失败!');
            }
          })
        },
        handleItemDelete: function(index,row){   // 删除绑定变量项
          this.addForm.collectedParameterConfigurationEntities.splice(index,1)
        },
        onPickerChange: function(date){

        },
        onPageChange: function(page){
          this.currentPage =page
          this.askLists()
        },
        addSettingItem: function(){
          let _that = this
           if (!this.itemAddForm.paramsName) {
             this.$message("请输入参数名")
             return
           }
          if (!this.itemAddForm.attributeInfoId) {
            this.$message("请绑定变量")
            return
          }
          if (!this.addForm.collectedParameterConfigurationEntities) {
            this.addForm.collectedParameterConfigurationEntities = []
          }
          this.addForm.collectedParameterConfigurationEntities.push({
            attributeInfoId: _that.itemAddForm.attributeInfoId,
            tagName: _that.itemAddForm.tagName,
            parameter: _that.itemAddForm.paramsName
          })
          this.itemAddForm = {
            attributeInfoId: '',
            paramsName: '',
            tagName: ''
          }
        },
        askTagList: function(){
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let gateway = sessionStorage.getItem("gateway")
          let url = _that.ports.collectManage.collectBaseData.tagList
          let askData = {
            search: _that.searchStr,
            isCumulative: _that.isCumulative,
            userId: userId,
            current: 1,
            size: 1000,
            sn:gateway,
          }
          this.http.get(url,askData, res => {
            console.log("myTagLists",res)
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              if (res.data.records) {
                let arry = []
                for (let i = 0; i < res.data.records.length; ++i) {
                  arry.push({label:res.data.records[i].tagName,value:res.data.records[i].id})
                }
                _that.tagBindOptions = arry
                _that.tagList = res.data.records
              }
            }
          })
        },
        askLists: function(){
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let gateway = sessionStorage.getItem("gateway")
          let url = _that.ports.collectManage.collectData.lists
          let askData = {
            userId: userId,
            current: _that.currentPage,
            size: _that.pageSize,
            nodeName:_that.nodeName,
            isReportShow:_that.isReportShow,
            isCumulative:_that.isCumulative,
            sn: gateway
          }
          this.http.get(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.tableData = res.data.records
              _that.paginationCount = res.data.total
            }else{
              _that.$message('数据获取失败!');
            }
          })
        },
        addTagNode: function() {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let gateway = sessionStorage.getItem("gateway")
          let url = _that.ports.collectManage.collectData.add + "?userId=" + userId
          this.addForm.sn = gateway
          this.http.post(url,_that.addForm, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.addDialogShow = false
              _that.$message('新增成功!');
              _that.askLists()
            }else{
              _that.$message('新增失败!');
            }
          })
        },
        askInfo: function(id) {
          let _that = this
          let userId = sessionStorage.getItem("userId")
          let url = _that.ports.collectManage.collectData.info
          let askData = {
              userId: userId,
              id: id
          }
          this.http.get(url,askData, res => {
            if(!_that.validateGlobal.isEmpty(res) && res.code == 200){
              _that.addForm = res.data
              if (res.data.type) {
                _that.addForm.customType = res.data.type.split(',')
                // _that.$set(_that.addForm,'customType',res.data.type.split(',') )
              }
              if (res.data.isReportShow){
                _that.onIsReportSelect(res.data.isReportShow)
              }
            }else{
              _that.$message('信息查询失败!');
            }
          })
        }

      }
    }
</script>

<style lang="scss">

  #cpts-collect-datas{

    > .el-card{
      margin: 20px 20px 0 20px;
      height: 780px;
    }

    .el-dialog{
      height: 680px;
      width: 1400px;
    }

    .cdc-submit-layout{
      display: flex;
      justify-content: center;
    }

    .el-collapse-item__content {
      padding-bottom: 20px;
    }

    .el-input__inner {
      width: 300px;
    }

    #cpts-cds-chart{
      height: 500px;
      width: 100%;
    }
  }

</style>
